/**
 * Created by 白雨浓 on 2017/8/27 1:22.
 *
 * node request 封装 用于直接提交跨域请求
 */

const request = require('request');

const Http = {
    install(Vue){
        const get = (path, params) => {
            if (params !== undefined) {
                let b = true;
                for (const key of params) {
                    if (b) {
                        path += `?${key}=${params[key]}`;
                        b = !b;
                    }
                    else
                        path += `&${key}=${params[key]}`
                }
            }
            return new Promise((resolve, reject) => {
                request.get(path, (err, res, data) => {
                    if (err !== null) {
                        reject(err);
                    } else {
                        resolve([data, res]);
                    }
                });
            })
        };

        const post = (path, params) => {
            return new Promise((resolve, reject) => {
                request.post(path, (err, res, data) => {
                    if (err !== null) {
                        reject(err);
                    } else {
                        resolve([data, res]);
                    }
                }).form(params);
            })
        };

        Vue.prototype.$$http = {
            request,
            get,
            post,
        };
    }
};

export default Http;